<?php

require_once(sfConfig::get('sf_plugins_dir').'/sfDoctrineApplyPlugin/modules/sfApply/lib/BasesfApplyActions.class.php');
require_once(sfConfig::get('sf_lib_dir').'/vendor/EpiFramework/EpiCurl.php');
require_once(sfConfig::get('sf_lib_dir').'/vendor/EpiFramework/EpiOAuth.php');
require_once(sfConfig::get('sf_lib_dir').'/vendor/EpiFramework/EpiTwitter.php');

class sfApplyActions extends BasesfApplyActions
{
    public function executeApply(sfRequest $request)
    {
        if($this->getUser()->isAuthenticated()){
            $this->redirect('/nominaciones');
        }
        $this->form = $this->newForm('sfApplyApplyForm');
        if ($request->isMethod('post')) {
            
            $values = $request->getParameter('sfApplyApply');
            
            $this->form->bind($values);
            
            if ($this->form->isValid()) {
                $guid = "n" . self::createGuid();
                $this->form->setValidate($guid);
                $this->form->save();
                try {
                    $profile = $this->form->getObject();
                    $this->mail(array('subject' => sfConfig::get('app_sfApplyPlugin_apply_subject',
                    sfContext::getInstance()->getI18N()->__("Por favor valide su cuenta en %1%", array('%1%' => $this->getRequest()->getHost()))),
                    'fullname' => $profile->getFullname(),
                    'email' => $profile->getEmail(),
                    'parameters' => array('fullname' => $profile->getFullname(), 'validate' => $profile->getValidate()),
                    'text' => 'sfApply/sendValidateNewText',
                    'html' => 'sfApply/sendValidateNew'));
                    
                    return 'After';
                } catch (Exception $e) {
                //$mailer->disconnect();
                    $profile = $this->form->getObject();
                    $user = $profile->getUser();
                    $user->delete();
                // You could re-throw $e here if you want to 
                // make it available for debugging purposes
                    return $e; //'MailerError'
                }
            } else {                
                $errors = $this->form->getErrorSchema()->getErrors();
                
                if(count($errors) === 1 && isset($errors['email']) && 
                        stripos($errors['email'], 'Ya existe una cuenta con esa dirección de Email.') !== false){
                    
                    $stored_user = Doctrine::getTable('sfGuardUser')->findOneByEmailAddress($values['email']);
                    
                    if($stored_user && $stored_user->getFacebookData()) {
                        
                        $stored_user->setPassword($values['password']);
                        
                        $stored_user->setUsername($values['username']);
                        
                        $stored_user->save();
                        
                        $profile = $stored_user->getProfile();
                        
                        $profile->setFullname($values['fullname']);
                        
                        $profile->save();
                        
                        $user = $this->getUser();
                        
                        $user->signin($stored_user, true);
                        
                        $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $user->getReferer($request->getReferer()));

                        $this->redirect('' != $signinUrl ? $signinUrl : '@homepage');
                    }
                }
            }
        }
        
        $this->twitter = new EpiTwitter(sfConfig::get('app_twitter_consumer_key'), sfConfig::get('app_twitter_consumer_secret'));
        
        $fbconfig['appid' ]     = sfConfig::get('app_facebook_appid');
        $fbconfig['secret']     = sfConfig::get('app_facebook_secret');
        $fbconfig['baseurl']    = sfContext::getInstance()->getRouting()->generate('apply_facebook', array(), true);
        
        try {
            include_once sfConfig::get('sf_lib_dir').'/vendor/PHP-SDK-3.0-Graph-API-Facebook/facebook.php';
        } catch(Exception $o) {
            error_log($o);
        }
        // Create our Application instance.
        $facebook = new Facebook(array(
            'appId'  => $fbconfig['appid'],
            'secret' => $fbconfig['secret'],
            'cookie' => true,
        ));

        $this->fb_login_url = $facebook->getLoginUrl(
            array(
                'scope' => 'email,offline_access,publish_stream,user_about_me',
                'redirect_uri' => $fbconfig['baseurl']
            ));
    }
  
    protected function mail($options) {
        $required = array('subject', 'parameters', 'email', 'fullname', 'html', 'text');
        
        foreach ($required as $option) {
            if (!isset($options[$option])) {
                throw new sfException("Required option $option not supplied to sfApply::mail");
            }
        }
        $message = $this->getMailer()->compose();
        $message->setSubject($options['subject']);

        // Render message parts
        $message->setBody($this->getPartial($options['html'], $options['parameters']), 'text/html');
        $message->addPart($this->getPartial($options['text'], $options['parameters']), 'text/plain');
        $address = $this->getFromAddress();
        $message->setFrom(array($address['email'] => $address['fullname']));
        $message->setTo(array($options['email'] => $options['fullname']));
        $this->getMailer()->send($message);
    }

    static private function createGuid()
    {
        $guid = "";
        for ($i = 0; ($i < 8); $i++) {
            $guid .= sprintf("%02x", mt_rand(0, 255));
        }
        return $guid;
    }
}